<template>
  <div>
    <cus-modal ref="modal" :title="this.form.id ? '编辑用户' : '添加用户'" @on-visible-change="onVisibleChange" @onOk="onOk">
      <Form ref="formValidate" :model="form" :rules="ruleValidate" :label-width="100">
        <FormItem label="姓名" prop="name" :label-width="100" :rules="{
          required: true,
          max: 20,
          message: '姓名不能为空',
          trigger: 'blur',
        }">
          <label slot="label">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名</label>
          <Input v-model="form.name" maxlength="20" clearable style="width: 200px;" placeholder="请输入姓名"></Input>
        </FormItem>
        <FormItem v-if="!form.id" label="登录账号" prop="loginName" :rules="{
          required: true,
          min: 5,
          max: 32,
          message: '请输入5-32位字母或数字',
          trigger: 'blur',
        }
       ">
         <Input v-model="form.loginName" maxlength="32" clearable style="width: 200px" placeholder="5-32位字母或数字"></Input>
        </FormItem>
        <FormItem label="联系电话" prop="phoneNumber" :rules="[
        { required: true,pattern: '^(0[0-9]{2,3}-[0-9]{7,8})$|^1[3456789][0-9]{9}$',
              message: '手机/电话号码格式不正确',
              trigger: 'blur'
            }
        ]">
          <Input v-model="form.phoneNumber" maxlength="20" clearable style="width: 200px" placeholder="请输入联系电话"></Input>
        </FormItem>
        <FormItem label="单位" prop="" :rules="{ required: true, message: '单位不能为空', trigger: 'blur' }">
          <label slot="label">单&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;位</label>
          <Input clearable style="width: 200px;" maxlength="20" disabled :value="vuex_user.base.unitName" placeholder="请输入单位"></Input>
        </FormItem>
        <FormItem label="职务" prop="postName" :rules="{ required: true, message: '职务不能为空', trigger: 'blur' }">
          <label slot="label">职&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;务</label>
          <Input v-model="form.postName" maxlength="20" clearable style="width: 200px; " placeholder="请输入职务"></Input>
        </FormItem>
        <!--
          <FormItem label="登录密码" prop="password" :rules="{required: true, message: '登录密码不能为空', trigger: 'blur'}">
            <Input v-model="form.password" type="password" clearable style="width: 200px" placeholder="请输入登录密码"></Input>
          </FormItem>-->
        <FormItem label="所属角色" prop="roleNameList" :rules="{
          required: true,
          type: 'array',
          min: 1,
          message: '角色不能为空',
          trigger: 'change',
        }">
          <CheckboxGroup style="
                      height: 40px;
                      line-height: 40px;
                      display: flex;
                      width: 550px;
                      flex-wrap: wrap;
               " v-model="form.roleNameList" @on-change="getSelectRole">
            <Checkbox v-for="(item, index) of roleList" :value="item.id" :key="item.id" :label="item.name"></Checkbox>
          </CheckboxGroup>
        </FormItem>
      </Form>
      <div style="margin-left: 10px; display: flex; align-items: center">
        <Icon type="ios-alert" size="20" style="margin-right: 10px" color="orange" />
        新增用户默认密码为：12345
      </div>
      <Spin size="large" fix v-if="loading"></Spin>
    </cus-modal>
  </div>
</template>
  
<script>
import {
  getUserInfo,
  addUser,
  modifyUser,
  getRoleListUnit,
  userRelevanceRole,
} from "@/api/organ/system";

const form = {
  id: "",
  name: "",
  loginName: "",
  phoneNumber: "",
  postName: "", //职务
  unitName: "", //单位
  password: "",
  descr: "",
  roleNameList: [], //角色名称
  roleIdList: [], //角色id
};

export default {
  name: "userModal",
  data() {
    return {
      loading: false,
      form: form,
      roleList: [],
      ruleValidate: {
      },
    };
  },
  mounted() {
    this.form = this.$cu.deepClone(form);
    console.log('1', this.form.id);
  },
  methods: {
    onVisibleChange(v) {
      this.$refs["formValidate"].resetFields();
      if (!v) this.form = this.$cu.deepClone(form);

      console.log('1', this.form.id);
    },
    show() {
      this.loading = false;
      console.log('1', this.form.id);
      this.$refs["modal"].show = true;
      let task = [this.getRoleListUnitApi()];
      console.log(this.form.id);
      if (this.form.id) {
        this.loading = true;
        task.push(this.getUserInfoApi());
      }
      Promise.all(task).then(() => {
        this.loading = false;
      });
    },
    onOk() {
      this.$refs["formValidate"].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.form.id) {
            this.modifyUserApi();
          } else this.addUserApi();
        }
      });
    },
    // 选择角色
    getSelectRole(val) {
      console.log(val);
      this.form.roleIdList = [];
      console.log(this.roleList);
      this.roleList.forEach((item) => {
        if (this.form.roleNameList.indexOf(item.name) != -1) {
          this.form.roleIdList.push(item.id);
        }
      });

      console.log(this.form.roleIdList);
    },
    // 获取用户详情
    getUserInfoApi() {
      console.log("11111111111111", this.roleList);
      return new Promise((resolve) => {
        getUserInfo({ id: this.form.id }).then((res) => {
          if (res.code === 1) {
            // 根据角色获取的权限id列表转换成权限名称列表
            this.form.id = res.data.base.id;
            this.form.name = res.data.base.name;
            this.form.postName = res.data.base.postName;
            this.form.phoneNumber = res.data.base.phoneNumber
            this.form.roleNameList = []
            this.roleList.forEach((item) => {
              console.log(res.data.list.indexOf(item.id));
              if (res.data.list.indexOf(item.id) != -1) {
                this.form.roleNameList.push(item.name);
                this.form.roleIdList.push(item.id)
              }
            });
            console.log("11111", this.form.name);
            resolve();
          }
        });
      });
    },

    // 获取角色列表(下拉框)
    getRoleListUnitApi() {
      return new Promise((resolve) => {
        getRoleListUnit({
          currentPage: 1,
          pageSize: 1000,
        }).then((res) => {
          if (res.code === 1) {
            this.roleList = res.data.list;
            console.log("角色", this.roleList);
            resolve();
          }
        });
      });
    },
    // 添加用户接口
    addUserApi() {
      console.log(this.form);
      return new Promise((resolve) => {
        addUser({
          loginName: this.form.loginName,
          password: "12345",
          name: this.form.name,
          phoneNumber: this.form.phoneNumber,
          postName: this.form.postName,
          unitCode: this.vuex_user.base.unitCode,
          descr: this.form.descr,
        }).then((res) => {
          if (res.code === 1) {
            this.form.id = res.data;
            this.userRelevanceRoleApi().then(() => {
              this.loading = false;
              this.$Message.success("添加成功");
              this.$refs["modal"].show = false;
              this.$parent.onInit();
            });
            resolve();
          } else this.loading = false;
        });
      });
    },
    // 编辑用户接口
    modifyUserApi() {
      console.log(this.form.roleIdList);
      return new Promise((resolve) => {
        modifyUser({
          id: this.form.id,
          loginName: this.form.loginName,
          password: this.form.password,
          name: this.form.name,
          phoneNumber: this.form.phoneNumber,
          postName: this.form.postName,
          descr: this.form.descr,
        }).then((res) => {
          if (res.code === 1) {
            this.userRelevanceRoleApi().then(() => {
              this.loading = false;
              this.$Message.success("编辑成功");
              this.$refs["modal"].show = false;
              this.$parent.onInit();
            });
            resolve();
          } else this.loading = false;
        });
      });
    },
    // 用户关联角色
    userRelevanceRoleApi() {
      return new Promise((resolve) => {
        userRelevanceRole({
          userId: this.form.id,
          roleList: JSON.stringify(this.form.roleIdList),
        }).then((res) => {
          if (res.code === 1) {
            resolve();
          } else this.loading = false;
        });
      });
    },
  },
};
</script>
  
<style scoped lang="less">
.permission {
  height: 300px;
  width: 500px;
  border: 1px solid #dcdee2;
  overflow-y: auto;
  border-radius: 2px;
  padding: 0 0 0 10px;
}
</style>
  